# encoding: utf-8

import os

import logging
import time

from utils.yamltool import sysConf, LogFilePath

logConf = sysConf.get('log')


class Logger:

	def __init__(self, filename=None, logger_name=None):
		if filename is None:
			filename = 'main.{}.log'.format(time.strftime("%y%m%d"))
		else:
			filename = filename + '.{}.log'.format(time.strftime("%y%m%d"))
		self.logger = logging.getLogger(logger_name)
		# 设置日志等级
		self.logger.setLevel(logConf.get('level'))
		# 日志格式化
		fmt = logging.Formatter(logConf.get('formatter'))
		# 创建 TimedRotatingFileHandler 对象用于拆分日志
		# time_rotating_handler = TimedRotatingFileHandler(filename=filename, when='midnight', backupCount=30)
		# 控制台处理器
		console_handle = logging.StreamHandler()
		# 设置控制台输出格式
		console_handle.setFormatter(fmt)
		# logger 添加控制器
		self.logger.addHandler(console_handle)
		# self.logger.addHandler(time_rotating_handler)

		# 文件处理器
		file_handle = logging.FileHandler(filename=str(os.path.join(LogFilePath, filename)), encoding='utf-8')
		file_handle.setFormatter(fmt)
		self.logger.addHandler(file_handle)

	@property
	def get_log(self):
		return self.logger


log = Logger().get_log
